package com.itic.mall.mobile.image;

import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.framework.utils.AdImageUtils;
import com.itic.appbase.framework.utils.NumberStringHelper;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.AdImageUtils.Param;
import com.itic.mall.mobile.base.BaseMobileInterface;
import com.itic.mall.mobile.jd.MallJdUtils;
import com.itic.mall.system.product.persistence.model.Product;
import com.itic.mall.system.product.service.ProductService;
import com.itic.mall.system.productjd.persistence.model.ProductJd;
import com.itic.mall.system.productjd.service.ProductJdService;

/**
 * 
 * 友惠家商城中心接口类
 * 
 * 
 * 
 * @author 许小宝 2017年07月25日 14时11分
 * 
 */
@Controller
@RequestMapping(value = "/mobile/image")
public class MallImageInterface extends BaseMobileInterface {
    @Autowired private ProductService productService;
    @Autowired private ProductJdService productJdService;
    /**
     * APP获取服务服务器URL
     * 
     * @return
     */
    @RequestMapping(value = "/url")
    @ResponseBody
    public Map<String, Object> url(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String result = FAIL;
        String errorCode = PARAM_ERROR_CODE;
        String errorMsg = PARAM_ERROR_MSG;
        try {
            String url = sysSettingService.getByKey("IMAGE_SERVER_URL");
            resultMap.put(DATA, url);
            result = SUCCESS;
            errorCode = SUCCESS_ERROR_CODE;
            errorMsg = SUCCESS_ERROR_MSG;
        } catch (Exception e) {
            errorCode = SERVER_ERROR_CODE;
            errorMsg = SERVER_ERROR_MSG;
            logException("MallImageInterface", "url", e.toString(), "获取图片服务器的URL", e);

        }
        resultMap.put(RESULT, result);
        resultMap.put(ERROR_CODE, errorCode);
        resultMap.put(ERROR_MSG, errorMsg);
        isCrrossDomain(response);
        return resultMap;
    }

    /**
     * 合成图片
     * 
     * @return
     */
    @RequestMapping(value = "/merge")
    public void merge(HttpServletRequest request, HttpServletResponse response, String spuId, String marketUserProductId ) {
        ServletOutputStream os = null;
        try {
            Product product = productService.get(spuId);
            product = filterPrice(product);
            Param param = new Param();
            
            param.setFingerprintImageFilepath(request.getServletContext().getRealPath("/static/images/ad/fingerprint.png"));
            if( StringHelper.isNotBlank(product.getProductHongbao()) && NumberStringHelper.isGreaterNoEqual(product.getProductHongbao(), "0") ){
            	param.setHongbaoImageFilepath(request.getServletContext().getRealPath("/static/images/ad/hongbao.png"));
            }else{
            	param.setHongbaoImageFilepath(request.getServletContext().getRealPath("/static/images/ad/hongbaonull.png"));
            }
            param.setMainImageUrl(product.getMainImageUrl());// 主图
            param.setHongbao(product.getProductHongbao());// 红包金额
            param.setPreferentialPrice(product.getProductPrice());// 优惠价格
            param.setOriginalPrice(product.getProductOrginPrice());// 商品原价
            
            param.setProductName(product.getName());// 商品名称
            param.setProductDesc(product.getNote());//推荐理由
            param.setSalesVolume(0);// 销量
            param.setQrCode(sysSettingService.getByKey("MALL_SHARE_PRODUCT") + spuId + "&marketUserProductId=" + marketUserProductId );
            BufferedImage image = AdImageUtils.gen(param);
            response.setContentType("image/jpeg");
            response.addHeader("Content-Disposition", "attachment;filename=" + spuId + ".jpg");
            os = response.getOutputStream();
            ImageIO.write(image, "jpg", os);
        } catch (Exception e) {
            logException("MallImageInterface", "merge", e.toString(), "合成图片", e);
        } finally {
            IOUtils.closeQuietly(os);
        }
    }

    
    /**
     * 合成图片
     * 
     * @return
     */
    @RequestMapping(value = "/mergeYun")
    public void mergeYun(HttpServletRequest request, HttpServletResponse response, String spuId, String marketUserProductId, String yunId ) {
        ServletOutputStream os = null;
        try {
            Product product = productService.get(spuId);
            product = filterPrice(product);
            Param param = new Param();
            param.setFingerprintImageFilepath(request.getServletContext().getRealPath("/static/images/ad/fingerprint.png"));
            if( StringHelper.isNotBlank(product.getProductHongbao()) && NumberStringHelper.isGreaterNoEqual(product.getProductHongbao(), "0") ){
            	param.setHongbaoImageFilepath(request.getServletContext().getRealPath("/static/images/ad/hongbao.png"));
            	param.setHongbao(product.getProductHongbao());// 红包金额
            }else{
            	param.setHongbaoImageFilepath(request.getServletContext().getRealPath("/static/images/ad/hongbaonull.png"));
            	param.setHongbao("");// 红包金额
            }
            param.setMainImageUrl(product.getMainImageUrl());// 主图
            
            param.setPreferentialPrice(product.getProductPrice());// 优惠价格
            param.setOriginalPrice(product.getProductOrginPrice());// 商品原价
            
            param.setProductName(product.getName());// 商品名称
            param.setProductDesc(product.getNote());//推荐理由
            param.setSalesVolume(0);// 销量
            param.setQrCode(sysSettingService.getByKey("MALL_SHARE_PRODUCT") + spuId + "&marketUserProductId=" + marketUserProductId + "&yunId="+yunId );
            BufferedImage image = AdImageUtils.gen(param);
            response.setContentType("image/jpeg");
            response.addHeader("Content-Disposition", "attachment;filename=" + spuId + ".jpg");
            os = response.getOutputStream();
            //image.flush();
            ImageIO.write(image, "jpg", response.getOutputStream()); 
            
            
            
        } catch (Exception e) {
            logException("MallImageInterface", "mergeYun", e.toString(), "合成店主图片", e);
        } finally {
            IOUtils.closeQuietly(os);
        }
    }
    
    
    /**
     * 合成图片
     * 
     * @return
     */
    @RequestMapping(value = "/mergeJd")
    public void mergeJd(HttpServletRequest request, HttpServletResponse response, String spuId, String marketUserProductId, String yunId ) {
        ServletOutputStream os = null;
        try {
            ProductJd productJd = productJdService.get(spuId);
            
            Param param = new Param();
            param.setFingerprintImageFilepath(request.getServletContext().getRealPath("/static/images/ad/fingerprint.png"));
            if( StringHelper.isNotBlank(productJd.getConTicketPrice()) && NumberStringHelper.isGreaterNoEqual(productJd.getConTicketPrice(), "0")  ){
            	param.setHongbaoImageFilepath(request.getServletContext().getRealPath("/static/images/ad/hongbao.png"));
            }else{
            	param.setHongbaoImageFilepath(request.getServletContext().getRealPath("/static/images/ad/hongbaonull.png"));
            }
            param.setMainImageUrl(productJd.getGoodsUrl());// 主图
            param.setHongbao(productJd.getConTicketPrice());// 红包金额
            param.setPreferentialPrice(productJd.getConPrice());// 优惠价格
            param.setOriginalPrice(productJd.getOriPrice());// 商品原价
            
            param.setProductName(productJd.getGoodsName());// 商品名称
            param.setProductDesc(productJd.getProDesc());//推荐理由
            param.setSalesVolume(0);// 销量
            String convertResult = MallJdUtils.convert(yunId, productJd.getSku(), productJd.getConUrlB() );
            if( StringHelper.isBlank(convertResult) ){
				 //没有优惠卷就没有咯
          	    String tgwIdByTgwName = getTgwIdByTgwName(yunId);
          	    if( !StringHelper.isNotBlank(tgwIdByTgwName) ){
          	    	tgwIdByTgwName = getTgwIdByTgwName("0");
          	    }
          	    String subConvert = MallJdUtils.subConvert(productJd.getSku(), tgwIdByTgwName);
      	    	if( null != subConvert ){
      	    		convertResult = subConvert;
      	    	}
			}
            param.setQrCode( convertResult );
            
            BufferedImage image = AdImageUtils.genJd(param);
            response.setContentType("image/jpeg");
            response.addHeader("Content-Disposition", "attachment;filename=" + spuId + ".jpg");
            os = response.getOutputStream();
            ImageIO.write(image, "jpg", os);
        } catch (Exception e) {
            logException("MallImageInterface", "mergeJd", e.toString(), "合成京东图片", e);
        } finally {
            IOUtils.closeQuietly(os);
        }
    }
    

}